$(function(){
$(".option").on("mousedown",function(){
			$(this).addClass("mouseOn");
		}).on("mouseup",function(){
			$(this).removeClass("mouseOn");
		}).on("click",function(){
	if($(".hidden-options").css("visibility")=="hidden"){//如果当前隐藏
		$(".hidden-options").css("visibility","visible");//那么就显示div
	} 
	else{
		$(".hidden-options").css("visibility","hidden");//就隐藏div
		}
});

var levelNow=0;//当前难度等级
var imgregion = $(".chart");//图片显示区域
var imgCells = '';
var hasStart = 0;//记录有是否开始的变量，默认fasle，未开始
var levelArr = [[3,3],[4,4],[6,6]];//存储难度等级的数组
var scoreArr = [100,200,400];//存储难度等级分数的数组
var score=0;
var imgOrigArr = [];//图片拆分后，存储正确排序的数组
var imgRandArr = [];//图片打乱顺序后，存储当前排序的数组
//图片整体的宽高
var imgWidth = parseInt(imgregion.css("width"));
var imgHeight = parseInt(imgregion.css("height"));
var img="img/Jigsawpuzzle.jpg";//拼图图片
//拆分后每个方格的宽高
var cellWidth = imgWidth/levelArr[levelNow][0];//获取方格的宽度
var cellHeight = imgHeight/levelArr[levelNow][1];//获取方格的高度
var btnoption = $(".number");//选项按钮数字
var btnLevel = $(".hidden-options>li");//隐藏选项按钮
var btnStart = $(".start");
var frequency=$("#frequency");
var _frequency=0;
var _fraction=$("#fraction");
$(".hidden-options>li").filter(":first").on("mousedown",function(){
			$(this).addClass("mouseOn");
		}).on("mouseup",function(){
			$(this).removeClass("mouseOn");
		}).on("click",function(){
			
	$(".hidden-options").css("visibility","hidden");
	$(".number").html($(this).html());
	levelNow=0;
	levelSelect();
	
});
$(".hidden-options>li").filter(":nth-of-type(2)").on("mousedown",function(){
			$(this).addClass("mouseOn");
		}).on("mouseup",function(){
			$(this).removeClass("mouseOn");
		}).on("click",function(){
			
	$(".hidden-options").css("visibility","hidden");
	$(".number").html($(this).html());
	levelNow=1;
	levelSelect();
	
});
$(".hidden-options>li").filter(":nth-of-type(3)").on("mousedown",function(){
			$(this).addClass("mouseOn");
		}).on("mouseup",function(){
			$(this).removeClass("mouseOn");
		}).on("click",function(){
			
	$(".hidden-options").css("visibility","hidden");
	$(".number").html($(this).html());
	levelNow=2;
	levelSelect();
	
});
//显示或隐藏选项
imgSplit();
function levelSelect(){
//			判断是否在游戏中
			if(hasStart){
				if(!confirm("正在游戏中，确定要改变游戏难度吗？")){
					return false;
				}else{
					hasStart = false;
					btnStart.text("开始");
				}
			}
			imgregion.html("");
			cellWidth = imgWidth/levelArr[levelNow][1];
			cellHeight = imgHeight/levelArr[levelNow][0];
			imgSplit();
}

function imgSplit(){
		imgOrigArr = [];//清空正确排序的数组	
//		imgOrigArr.html=""; 
		var cell = "";//记录单个图片方格的变量
		for(var i=0;i<levelArr[levelNow][0];i++){
			for(var j=0;j<levelArr[levelNow][1];j++){
				//将方格所属div的下标存入数组
				imgOrigArr.push(i*levelArr[levelNow][1]+j);
				cell = document.createElement("li");
				cell.className = "square-background";
				$(cell).css({
					"width":(cellWidth) + "px",
					"height":(cellHeight) + "px",
					"left":j * cellWidth + "px",
					"top":i * cellHeight + "px",
					"background":"url("+img+")",
					"backgroundPosition":(-j)*cellWidth + "px " + (-i)*cellHeight + "px"
				});
				imgregion.append(cell);
			}
		}//动态获取显示图片
		imgCells=$(".square-background");
	}	
function game(){
				if(hasStart == 0){//不在游戏中
				//开始游戏后部分值、样式设置
				btnStart.text("恢复");
				hasStart = 1;
				//打乱图片
				randomArr();
				cellOrder(imgRandArr);

				//图片事件
				imgCells.css(
					"cursor","pointer"
				).on("mouseover",function(){
					$(this).addClass("hover");
				}).on("mouseout",function(){
					$(this).removeClass("hover");
				}).on("mousedown",function(e){
					/*此处是图片移动*/
					$(this).css("cursor","move");
				//所选图片方格的下标以及鼠标相对该方格的位置
					var cellIndex_1 = $(this).index();
					var cell_mouse_x = e.pageX - imgCells.eq(cellIndex_1).offset().left;
					var cell_mouse_y = e.pageY - imgCells.eq(cellIndex_1).offset().top;

					$(document).on("mousemove",function(e2){
						imgCells.eq(cellIndex_1).css({
							"z-index":"40",
							"left":(e2.pageX - cell_mouse_x - imgregion.offset().left) + "px",
							"top":(e2.pageY - cell_mouse_y - imgregion.offset().top) + "px",
						});
					}).on("mouseup",function(e3){
						//被交换的方格下标
						var cellIndex_2 = cellChangeIndex((e3.pageX-imgregion.offset().left),(e3.pageY-imgregion.offset().top),cellIndex_1);
						
						//方格交换
						if(cellIndex_1 == cellIndex_2){
							cellReturn(cellIndex_1);
						}else{
							cellExchange(cellIndex_1,cellIndex_2);
						}
						//移除绑定
						$(document).off("mousemove").off("mouseup");
					});
				}).on("mouseup",function(){
					$(this).css("cursor","pointer");
				});
			}else{
				//样式恢复
				btnStart.text("开始");
				hasStart = 0;

				//复原图片
				cellOrder(imgOrigArr);

				//取消事件绑定
				imgCells.css("cursor","default").off("mouseover").off("mouseout").off("mousedown");				
			}
	
}
function randomArr(){
		//清空数组
		imgRandArr = [];

		var order;//记录随机数，记录图片放置在什么位置
		for(var i=0,len=imgOrigArr.length;i<len;i++){
			order = Math.floor(Math.random()*len);
			if(imgRandArr.length > 0){
				while(jQuery.inArray(order,imgRandArr) > -1){
					order = Math.floor(Math.random()*len);
				}
			}
			imgRandArr.push(order);
		}
		return;
};
	
function cellOrder(arr){
		for(var i=0,len=arr.length;i<len;i++){
			imgCells.eq(i).animate({
				'left': arr[i]%levelArr[levelNow][0]*cellWidth + 'px',
				'top': Math.floor(arr[i]/levelArr[levelNow][1])*cellHeight + 'px'
			},500);
		}
	}//复原图片

function cellChangeIndex(x,y,orig){
		//鼠标拖动碎片移至大图片外
		if(x<0 || x>imgWidth || y<0 || y>imgHeight){
			return orig;
		}
		//鼠标拖动碎片在大图范围内移动
		var row = Math.floor(y/cellHeight),col = Math.floor(x/cellWidth),location=row*levelArr[levelNow][1]+col;
		var i=0,len=imgRandArr.length;
		while((i<len) && (imgRandArr[i] != location)){
			i++;
		}
		return i;
	}

function cellExchange(from,to){
		//被拖动图片、被交换图片所在行、列
		var rowFrom = Math.floor(imgRandArr[from]/levelArr[levelNow][1]);
		var colFrom = imgRandArr[from]%levelArr[levelNow][1];
		var rowTo = Math.floor(imgRandArr[to]/levelArr[levelNow][1]);
		var colTo = imgRandArr[to]%levelArr[levelNow][1];

		var temp = imgRandArr[from];//被拖动图片下标，临时存储

		//被拖动图片变换位置
		imgCells.eq(from).animate({
			'top':rowTo*cellHeight + 'px',
			'left':colTo*cellWidth + 'px'
		},500,function(){
			$(this).css('z-index','10');
		});
		//表交换图片变换位置
		imgCells.eq(to).css('z-index','30').animate({
			'top':rowFrom*cellHeight + 'px',
			'left':colFrom*cellWidth + 'px'
		},500,function(){
			$(this).css('z-index','10');
			//两块图片交换存储数据
			imgRandArr[from] = imgRandArr[to];
			imgRandArr[to] = temp;
		frequency.html(++_frequency);
			//判断是否完成全部移动，可以结束游戏
			if(checkPass(imgOrigArr,imgRandArr)){
				btnStart.text("开始");
				hasStart=0;
				alert("你他娘的还真是个天才");
				frequency.html(_frequency-1);
				score+=scoreArr[levelNow];
				_fraction.html(score);
				//取消事件绑定
				imgCells.css("cursor","default").off("mouseover").off("mouseout").off("mousedown");		
			}
		});
		
			
	}

function cellReturn(index){
		var row = Math.floor(imgRandArr[index]/levelArr[levelNow][1]);
		var col = imgRandArr[index]%levelArr[levelNow][1];

		imgCells.eq(index).animate({
			'top':row*cellHeight + 'px',
			'left':col*cellWidth + 'px'
		},500,function(){
			$(this).css('z-index','10');
		});
	}

function checkPass(rightArr,puzzleArr){
		if(rightArr.toString() == puzzleArr.toString()){
			return true;
		}
		return false;
	}//判断游戏是否成功的函数
btnStart.on("mousedown",function(){
	$(this).addClass("mouseOn");}).on("mouseup",function(){
		$(this).removeClass("mouseOn");
	}).on("click",function(){
	game();
	frequency.html("0")
})
});
